# !usr/bin/env python
# -*- coding:utf-8 -*-
import sys
from PyQt5 import QtWidgets
from mainwindow import Ui_MainWindow
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QLCDNumber, QCheckBox, QPushButton

uart_name_list= list()
count = int(0)
uart_desc_list = list()
speed = int(30)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
	def __init__(self, parent = None):
		super(MainWindow, self).__init__(parent)
		self.setupUi(self)
		self.uart_init()
		self.display_angle_init()
		self.setSignalSlot()
		self.set_turn_speed()

	def uart_init(self):
		global uart_name_list, uart_desc_list, count
		self.com = QSerialPort()
		port_numb = QSerialPortInfo.availablePorts()
		for info in port_numb:
			if info.portName().count('COM', 0, len(info.portName())) != 0:
				uart_str_desc = info.description().split()
				# print("uart_str_desc= %s" % uart_str_desc)
				uart_str_name = info.portName().split()
				uart_name_list.append(uart_str_name[0])
				uart_desc_list.append(uart_str_desc[0])
				# print("uart_desc_list= %s" % uart_desc_list)

		else:
			# print("uart_desc_list = %s" % uart_desc_list)
			# print("uart_name_list = %s" % uart_name_list)
			count = str(uart_name_list).count('COM', 0, len(str(uart_name_list)))
			# print("count= %s" % count)
			if count > 256:
				QMessageBox.critical(self, '错误', '连接串口太多')
			else:
				self.cmb_port.clear()
				for i in range(0, count):
					self.cmb_port.addItem(uart_name_list[i] + ' ' + uart_desc_list[i])

	def setSignalSlot(self):
		self.btn_open.clicked.connect(self.btn_open_port)
		self.btn_close.clicked.connect(self.btn_close_port)
		self.btn_turnleft.pressed.connect(self.send_turn_left)      # 发送左转
		self.btn_turnright.pressed.connect(self.send_turn_right)    # 发送右转
		self.btn_turnup.pressed.connect(self.send_turn_up)
		self.btn_turndown.pressed.connect(self.send_turn_down)
		self.btn_turnleft.released.connect(self.send_turn_stop)     # 发送停止
		self.btn_turnright.released.connect(self.send_turn_stop)
		self.btn_turnup.released.connect(self.send_turn_stop)
		self.btn_turndown.released.connect(self.send_turn_stop)
		self.btn_start.clicked.connect(self.btn_started)
		self.btn_stop.clicked.connect(self.btn_stoped)
		self.com.readyRead.connect(self.display_angle)

	def btn_open_port(self):
		global uart_desc_list, uart_name_list, count
		for i in range(0, count):
			if (uart_name_list[i] + ' ' + uart_desc_list[i]) == self.cmb_port.currentText():
				self.com.setPortName(uart_name_list[i])
		self.com.setBaudRate(QSerialPort.Baud115200)
		self.com.setDataBits(QSerialPort.Data8)
		self.com.setStopBits(QSerialPort.OneStop)
		self.com.setParity(QSerialPort.NoParity)
		self.com.open(QSerialPort.ReadWrite)
		if self.com.isOpen():
			self.lab_status.setText("已连接")
		else:
			QMessageBox.critical(self, '错误', '串口打开失败')

	def btn_close_port(self):
		self.com.close()
		self.lab_status.setText("未连接")

	def send_turn_left(self):
		global speed
		self.set_turn_speed()
		tx_data_left = bytearray([0xff, 0x01, 0x00, 0x04, speed, 0x00, 0x42])
		self.com.write(tx_data_left)

	def send_turn_right(self):
		global speed
		self.set_turn_speed()
		tx_data_right = bytearray([0xff, 0x01, 0x00, 0x02, speed, 0x00, 0x42])
		self.com.write(tx_data_right)

	def send_turn_up(self):
		global speed
		self.set_turn_speed()
		tx_data_up = bytearray([0xff, 0x01, 0x00, 0x08, 0x00, speed, 0x48])
		self.com.write(tx_data_up)

	def send_turn_down(self):
		global speed
		self.set_turn_speed()
		tx_data_down = bytearray([0xff, 0x01, 0x00, 0x10, 0x00, speed, 0x50])
		self.com.write(tx_data_down)

	def send_turn_stop(self):
		if not self.btn_turnleft.isDown() and not self.btn_turnright.isDown() and not self.btn_turnup.isDown() and not self.btn_turndown.isDown():
			tx_data_stop = bytearray([0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01])
			self.com.write(tx_data_stop)

	def btn_started(self):
		y_axis_data = self.i_le_y_axis.text()       # QLineEdit输入的字符串
		if len(y_axis_data) == 0:
			QMessageBox.critical(self, '错误', '角度不能为空')
		else:
			y_axis_data = int(y_axis_data, base=10)     # str->dec
			y_axis_data = y_axis_data * 100
			y_temp_h = (y_axis_data >> 8) & 0xff
			y_temp_l = y_axis_data & 0xff
			'''简单的校验和方式'''
			y_temp_sum = 0x01 + 0x00 + 0x4d + y_temp_h + y_temp_l
			if y_temp_sum > 0xff:
				y_temp_sum = ~ y_temp_sum
				y_temp_sum += 1
			y_temp_sum = y_temp_sum & 0xff
			y_tx_data = bytearray([0xff, 0x01, 0x00, 0x4d, y_temp_h, y_temp_l, y_temp_sum])
			self.com.write(y_tx_data)
		z_axis_data = self.i_le_z_axis.text()
		if len(z_axis_data) == 0:
			QMessageBox.critical(self, '错误', '角度不能为空')
		else:
			z_axis_data = int(z_axis_data)
			z_axis_data = z_axis_data * 100
			z_temp_h = (z_axis_data >> 8) & 0xff
			z_temp_l = z_axis_data & 0xff
			z_temp_sum = 0x01 + 0x00 + 0x4d + z_temp_h + z_temp_l
			if z_temp_sum > 0xff:
				z_temp_sum = ~ z_temp_sum
				z_temp_sum += z_temp_sum
			z_temp_sum = z_temp_sum & 0xff
			z_tx_data = bytearray([0xff, 0x01, 0x00, 0x4d, z_temp_h, z_temp_l, z_temp_sum])
			self.com.write(z_tx_data)

	def btn_stoped(self):
		tx_data_stop = bytearray([0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01])
		self.com.write(tx_data_stop)

	def display_angle_init(self):
		self.y_axis_angle.setDigitCount(6)  # 将显示位数设为3位
		self.y_axis_angle.setMode(QLCDNumber.Dec)  # 十进制显示
		self.y_axis_angle.setSegmentStyle(QLCDNumber.Flat)  # 字体显示模式
		self.z_axis_angle.setDigitCount(6)
		self.z_axis_angle.setMode(QLCDNumber.Dec)
		self.z_axis_angle.setSegmentStyle(QLCDNumber.Flat)

	def display_angle(self):
		rx_data = self.com.readLine(7)
		if rx_data[0] == 0xff and rx_data[1] == 0x01 and rx_data[2] == 0x00:
			if rx_data[3] == 0x59:  # 水平 Z轴
				temp_z_angle = (rx_data[4] << 8) + rx_data[5]
				temp_z_angle = temp_z_angle / 100
				self.z_axis_angle.display(temp_z_angle)
			elif rx_data[3] == 0x5b:    # 垂直 Y轴
				temp_y_angle = (rx_data[4] << 8) + rx_data[5]
				temp_y_angle = temp_y_angle / 100
				self.y_axis_angle.display(temp_y_angle)

	def set_turn_speed(self):
		cb_group = QButtonGroup()
		self.cb_speed1.setCheckable(True)
		self.cb_speed2.setCheckable(True)
		cb_group.addButton(self.cb_speed1, 0)
		cb_group.addButton(self.cb_speed2, 1)
		cb_group.setExclusive(True)         # 设置button互斥
		self.cb_speed1.clicked.connect(self.set_speed1)
		self.cb_speed2.clicked.connect(self.set_speed2)

	def set_speed1(self):
		global speed
		self.cb_speed1.setChecked(True)
		self.cb_speed2.setChecked(False)
		speed = int(46)

	def set_speed2(self):
		global speed
		self.cb_speed2.setChecked(True)
		self.cb_speed1.setChecked(False)
		speed = int(63)

if __name__ == "__main__":
	app = QtWidgets.QApplication(sys.argv)
	YunTab = MainWindow()
	YunTab.show()
	sys.exit(app.exec_())
	